#############################################
#This file creates Figure 1
#############################################

###Log
my_log <- file("figure1_log.txt")

sink(my_log, append=T, type="output")
sink(my_log, append=T, type="message")

cat(readChar(rstudioapi::getSourceEditorContext()$path, # Writing currently opened R script to file
             file.info(rstudioapi::getSourceEditorContext()$path)$size))

start_time <- Sys.time()
start_time

###Packages

library(foreign)
library(magrittr)
library(multcomp)
library(ggstance)
library(socviz)
library(rio)
library(broom)
library(margins)
library(tidyverse)

######################
#Process: 
#' Load each experiment; clean it; 
#' combine; run regressions as needed
#####################


############################
#Experiment 1
############################
####Load the data
exp1 <- import("./Data/exp1_cleaned.csv")


####Clean the data as needed
#DV
exp1$support01 <- scales::rescale(exp1$support)

#Treatment Condition
exp1 <- exp1 %>%
  mutate(treat = case_when(
    condition == "No Party Cue" ~ 1, 
    condition == "Party Cue" ~ 2, 
    condition == "Neg Process" ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

#Experiment
exp1$experiment <- "Experiment 1"
exp1$pol_exp <- "Air Traffic"
exp1$treat_policy <- NA

############################
#Experiment 2
############################

####Load the data
exp2 <- import("./Data/exp2_cleaned.csv")

####Clean the data as needed
#DV
exp2$support01 <- scales::rescale(exp2$policy_support)

#Treatment Condition(s)
exp2 <- exp2 %>%
  mutate(treat = case_when(
    treat_info == 1 ~ 1, 
    treat_info == 2 ~ 2, 
    treat_info == 4 ~ 3)) %>%
  mutate(treat = factor(treat, 
                        labels=c("No Party Cue", "Party Cue", 
                                 "Cue w/Insinuation")))

exp2$treat_policy <- factor(exp2$treat_policy, 
                            levels=c(0,1),
                            labels=c("Conservative Change", "Liberal Change"))


#Experiment
exp2$experiment <- "Experiment 2"
exp2$pol_exp <- NA
exp2$pol_exp[exp2$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp2$pol_exp[exp2$treat_policy=="Liberal Change" ] <- "Tax:Liberal"

############################
#Experiment 3
############################

####Load the data
exp3 <- import("./Data/exp3_cleaned.csv")

####Clean the data as needed
#restrict to partisans
exp3 <- exp3 %>%
  filter(pid_3 == "Democrat" | pid_3 == "Republican")

#DV
exp3$support01 <- scales::rescale(exp3$tax_support)

#Treatment Condition(s)
exp3$treat <- factor(exp3$treat_3, 
                     levels=c("No Party Cue", "Party Cue", "Party Cue w/ Group Pressure"), 
                     labels=c("No Party Cue", "Party Cue", "Cue w/Insinuation"))

exp3$treat_policy <- factor(exp3$change, 
                            levels=c("Conservative Change", "Liberal Change"))

#Experiment
exp3$experiment <- "Experiment 3"
exp3$pol_exp <- NA
exp3$pol_exp[exp3$treat_policy=="Conservative Change"] <- "Tax:Conservative"
exp3$pol_exp[exp3$treat_policy=="Liberal Change"] <- "Tax:Liberal"


############################
#Binding
############################

exp1a <- exp1 %>%
  dplyr::select(support01, treat, experiment, pol_exp, treat_policy) 

exp2a <- exp2 %>%
  dplyr::select(support01, treat, experiment, pol_exp, treat_policy)

exp3a <- exp3 %>%
  dplyr::select(support01, treat, experiment, pol_exp, treat_policy) 

pooled <- rbind(exp1a, exp2a, exp3a)

pooled <- pooled %>%
  mutate(experiment = factor(experiment,
                             levels=c("Experiment 1", "Experiment 2", "Experiment 3")))

export(pooled, "./Figure1/pooled.dta")
#Exporting so we can make nicer tables in STATA

############################
#Models
############################

############
#Pooled
############

#Study, Policy FE
pooled <- pooled %>%
  mutate(polissue = case_when(
    experiment == "Experiment 1" ~ 1, 
    experiment == "Experiment 2" & pol_exp == "Tax:Conservative" ~ 2,  
    experiment == "Experiment 2" & pol_exp == "Tax:Liberal" ~ 3, 
    experiment == "Experiment 3" & pol_exp == "Tax:Conservative" ~ 4, 
    experiment == "Experiment 3" & pol_exp == "Tax:Liberal" ~ 5), 
    polissue = factor(polissue, 
                      levels=c(1,2,3,4,5), 
                      labels=c("Experiment 1", "Exp 2: Conservative Change", 
                               "Exp 2: Liberal Change", "Exp 3: Conservative Change", 
                               "Exp 3: Liberal Change")))

#Model
m1 <- lm(support01 ~ treat + polissue,  data=pooled)

#Extracting Data for Subsequent Graph
coefs1 <- tidy(lm(support01 ~ treat + polissue,  data=pooled)) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs1$experiment <- "Pooled"
coefs1$comparison <- "Coefficient"
coefs1$term <-prefix_strip(coefs1$term, "treat")

##Getting Difference btwn Treatments Data
names(coef(m1))

lincom1 <- tidy(summary(glht(m1, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef",
         experiment = "Pooled") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom1


##############
#Experiment 1
##############

###Model 
m2 <- lm(support01 ~ treat, data = pooled, subset=(experiment == "Experiment 1"))


###Extracting Data
coefs2 <- tidy(lm(support01 ~ treat, data = pooled, subset=(experiment == "Experiment 1"))) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation")

coefs2$experiment <- "Experiment 1"
coefs2$comparison <- "Coefficient"
coefs2$term <-prefix_strip(coefs2$term, "treat")

#difference in treatment effects
names(coef(m2))

lincom2 <- tidy(summary(glht(m2, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 1") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom2

##############
#Experiment 2
##############
#Model
m3 <- lm(support01 ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 2"))

#Extracting Data
coefs3 <- tidy(lm(support01 ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 2"))) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs3$experiment <- "Experiment 2"
coefs3$comparison <- "Coefficient"
coefs3$term <-prefix_strip(coefs3$term, "treat")

#difference
lincom3 <- tidy(summary(glht(m3, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 2") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)


lincom3

##############
#Experiment 3
##############
#model
m4 <- lm(support01 ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 3"))

#Exacted data
coefs4 <- tidy(lm(support01 ~ treat + treat_policy, data = pooled, subset=(experiment == "Experiment 3"))) %>%
  filter(term == "treatParty Cue" | term == "treatCue w/Insinuation") 

coefs4$experiment <- "Experiment 3"
coefs4$comparison <- "Coefficient"
coefs4$term <-prefix_strip(coefs4$term, "treat")

#difference
lincom4 <- tidy(summary(glht(m4, linfct=c("`treatParty Cue` - `treatCue w/Insinuation` = 0")))) %>%
  mutate(term = "Cue - Cue w/Insinuation", 
         comparison = "Difference in Coef", 
         experiment = "Experiment 3") %>%
  dplyr::select(term, experiment, comparison, estimate, std.error, statistic, adj.p.value) %>%
  rename(p.value = adj.p.value)

lincom4


##############
#Binding
##############

results <- rbind(coefs1, lincom1, 
                 coefs2, lincom2, 
                 coefs3, lincom3, 
                 coefs4, lincom4)

results$sig <- if_else(results$p.value < 0.05, "Significant p < 0.05", 
                       "Insignificant p >= 0.05")


##############
#Figure
##############
results <- results %>% 
  mutate(experiment = factor(experiment, 
                             levels=c("Pooled", "Experiment 1", "Experiment 2", "Experiment 3")))


results %>%
  ggplot(aes(x=estimate, y=term, shape=sig)) + 
  geom_pointrangeh(aes(xmin=estimate-(1.96*std.error), xmax=estimate+(1.96*std.error))) + 
  theme_bw(18) + 
  facet_grid(comparison ~ experiment, scales="free_y", space="free_y", 
             labeller = label_wrap_gen(width = 15)) + 
  geom_text(data=results, aes(label=round(estimate,2)), 
            nudge_y=0.10) + 
  theme(strip.text.y = element_text(angle=0), 
        legend.position="bottom") + 
  scale_shape_manual(values=c(1,16)) + 
  labs(x = NULL,
       y = NULL, 
       shape = "Statistically Significant?") + 
  geom_vline(xintercept=0, 
             linetype="dashed", 
             color="red") + 
  scale_x_continuous(breaks=c(0, 0.1))


ggsave("./Figure1/figure1.png", height=7, width=14)

end_time <- Sys.time()
end_time


closeAllConnections()
